package com.zhijian.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhijian.entity.Portfolio;
import com.zhijian.entity.PortfolioComment;
import com.zhijian.entity.R;
import com.zhijian.entity.WxUserInfo;
import com.zhijian.service.IPortfolioService;
import com.zhijian.service.IPortfolioCommentService;
import com.zhijian.service.IWxUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/portfolio")
public class PortfolioController {

    @Autowired
    private IPortfolioService portfolioService;
    
    @Autowired
    private IPortfolioCommentService portfolioCommentService;

    @Autowired
    private IWxUserInfoService wxUserInfoService;

    /**
     * 获取作品集列表
     */
    @GetMapping("/list")
    public R list(@RequestParam(defaultValue = "1") Integer pageNum,
                 @RequestParam(defaultValue = "10") Integer pageSize,
                 @RequestParam(required = false) String keyword) {
        Page<Portfolio> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Portfolio> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like("title", keyword)
                .or()
                .like("description", keyword));
        }
        
        queryWrapper.orderByDesc("createTime");
        Page<Portfolio> page1 = portfolioService.page(page, queryWrapper);
        page1.getRecords().forEach(note -> {
            WxUserInfo wxUserInfo = wxUserInfoService.getById(note.getUserId());
            note.setWxUserInfo(wxUserInfo);
        });
        return R.ok().put("data", page1);
    }

    /**
     * 获取作品详情
     */
    @GetMapping("/detail/{id}")
    public R detail(@PathVariable Integer id) {
        Portfolio portfolio = portfolioService.getById(id);
        if (portfolio == null) {
            return R.error("作品不存在");
        }
        // 增加浏览量
        portfolio.setViews(portfolio.getViews() + 1);
        portfolioService.updateById(portfolio);
        WxUserInfo wxUserInfo = wxUserInfoService.getById(portfolio.getUserId());
        portfolio.setWxUserInfo(wxUserInfo);
        return R.ok().put("data", portfolio);
    }

    /**
     * 添加作品
     */
    @PostMapping("/add")
    public R add(@RequestBody Portfolio portfolio) {
        portfolio.setCreateTime(new Date());
        portfolio.setViews(0);
        portfolio.setComments(0);
        portfolio.setStatus(0);
        
        boolean success = portfolioService.save(portfolio);
        if (success) {
            return R.ok();
        } else {
            return R.error("添加失败");
        }
    }

    /**
     * 更新作品
     */
    @PostMapping("/update")
    public R update(@RequestBody Portfolio portfolio) {
        Portfolio existPortfolio = portfolioService.getById(portfolio.getId());
        if (existPortfolio == null) {
            return R.error("作品不存在");
        }
        
        boolean success = portfolioService.updateById(portfolio);
        if (success) {
            return R.ok();
        } else {
            return R.error("更新失败");
        }
    }

    /**
     * 删除作品
     */
    @PostMapping("/delete/{id}")
    public R delete(@PathVariable Integer id) {
        Portfolio portfolio = portfolioService.getById(id);
        if (portfolio == null) {
            return R.error("作品不存在");
        }
        portfolio.setStatus(1); // 设置为删除状态
        portfolioService.updateById(portfolio);
        return R.ok();
    }

    /**
     * 添加评论
     */
    @PostMapping("/comment/add")
    public R addComment(@RequestBody PortfolioComment comment) {
        // 设置创建时间
        comment.setCreateTime(new Date());
        
        // 保存评论
        portfolioCommentService.save(comment);
        
        // 更新作品评论数
        Portfolio portfolio = portfolioService.getById(comment.getPortfolioId());
        portfolio.setComments(portfolio.getComments() + 1);
        portfolioService.updateById(portfolio);
        
        return R.ok();
    }

    /**
     * 获取评论列表
     */
    @GetMapping("/comments/{portfolioId}")
    public R getComments(@PathVariable Integer portfolioId) {
        QueryWrapper<PortfolioComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("portfolioId", portfolioId)
                   .orderByDesc("createTime");
        List<PortfolioComment> list = portfolioCommentService.list(queryWrapper);
        list.forEach(noteComment -> {
            WxUserInfo wxUserInfo = wxUserInfoService.getById(noteComment.getUserId());
            noteComment.setWxUserInfo(wxUserInfo);
        });
        return R.ok().put("data", list);
    }
} 